<template>
  <view class="mxp-navbar" :style="{ background, position, zIndex, width: windowWidth }" @click="emits('click')">
    <view v-if="safeAreaInsetTop" :style="{ height: `${safeTopHeight}px` }"></view>
    <view class="navbar-vessel" :style="{ height: navHeight }">
      <view class="navbar-view" :style="{ height: navHeight, padding }">
        <view class="left-view" :style="{ height: navHeight }">
          <view v-if="showBack" :style="{ padding: '6px' }" @tap.stop.prevent="onBack">
            <mxp-icon name="zuojiantou" :size="leftIconSize" :color="leftIconColor || titleColor || '#303133'"></mxp-icon>
          </view>
          <slot name="left"></slot>
        </view>
        <view class="title-view" :style="{ width: titleWidth, height: navHeight, left: titleLeft }">
          <slot name="title">
            <text class="ellipsis title" style="font-size: 15px" :style="[newTitleStyle, titleTextStyle, { maxWidth: titleWidth }]">{{ title }}</text>
          </slot>
        </view>
        <view class="right-view" :style="{ height: navHeight }"><slot name="right"></slot></view>
      </view>
      <!-- 胶囊按钮占位 -->
      <view v-if="safeAreaInsetRight" class="right-placeholder" :style="{ width: menuButtonWidth + 'px' }"></view>
    </view>
    <mxp-line v-if="showLine" :cusStyle="{ position: 'absolute', bottom: '0px', left: '0px', zIndex: 1 }" :length="windowWidth" :color="borderColor"></mxp-line>
  </view>
  <view v-if="placeholder" :style="{ height: `${safeTopHeight + parseInt(navHeight)}px` }"></view>
</template>

<script lang="ts" setup>
  import { publicStyeProps } from '../mxp-tool/utils/public-props';
  import MxpIcon from '../mxp-icon/mxp-icon.vue';
  import MxpLine from '../mxp-line/mxp-line.vue';
  import { type CSSProperties, type PropType, computed, onMounted, ref } from 'vue';
  import type { $AllColorStr, $SizeUnitArr4Str, $SizeUnitStr } from '@/mxp-ui/mxp-tool/types/interface';
  import { getHeaderHeight, getXPNumber } from '../mxp-tool/utils/dom';
  import mxpGetSysInfoStore from '../mxp-tool/store/mxp-store-sys-info';
  defineOptions({
    name: 'mxp-navbar',
  });

  const props = defineProps({
    /** 导航栏标题，如设置为空字符，将会隐藏标题占位区域 */
    title: { type: [Number, String], default: '' },
    /** 标题宽度 */
    titleWidth: { type: String as PropType<$SizeUnitStr>, default: '180px' },
    /** 标题颜色 */
    titleColor: { type: String as PropType<$AllColorStr>, default: undefined },
    /** 标题粗体 */
    titleFontWeight: { type: [String, Number] as PropType<number | 'bold' | 'normal'>, default: undefined },
    /** 标题大小 */
    titleFontSize: { type: [String, Number] as PropType<number | 'bold' | 'normal'>, default: undefined },
    /** 标题颜色 */
    titleTextStyle: { type: Object as PropType<CSSProperties>, default: () => ({}) },
    /** 是否开启顶部安全区适配 */
    safeAreaInsetTop: { type: Boolean, default: true },
    /** 是否开起胶囊按钮安全区适配 */
    safeAreaInsetRight: { type: Boolean, default: true },
    /** 固定在顶部时，是否生成一个等高元素，以防止塌陷 */
    placeholder: { type: Boolean, default: true },
    /** 位置 */
    position: { type: String as PropType<'absolute' | 'fixed' | 'relative'>, default: 'fixed' },
    /** 标题栏下边框颜色 (如不需要边框可设为none)  */
    borderColor: { type: [Boolean, String] as PropType<$AllColorStr | boolean>, default: '#dadbde' },
    /** 背景色 */
    background: { type: String as PropType<$AllColorStr>, default: 'transparent' },
    /** 左侧返回图标的颜色 */
    leftIconSize: { type: String as PropType<$SizeUnitStr>, default: '16px' },
    /** 左侧返回图标的颜色 */
    leftIconColor: { type: String as PropType<$AllColorStr>, default: undefined },
    /** 边距 */
    padding: { type: String as PropType<$SizeUnitArr4Str>, default: '0px 15px' },
    /** 是否显示返回按钮 */
    showBack: { type: Boolean, default: true },
    /** 层级 */
    zIndex: { type: Number, default: 999 },
    /** 是否显示线条 */
    showLine: { type: Boolean, default: true },
    /** 首页的路径 */
    homePath: { type: String, default: undefined },
    ...publicStyeProps,
  });

  defineSlots<{
    /** 自定义标题 */
    title: () => void;
    /** 自定义左边内容 */
    left: () => void;
    /** 自定义右边内容 */
    right: () => void;
  }>();

  const emits = defineEmits<{
    (e: 'click'): void;
    (e: 'onBack'): void;
  }>();

  export type $PriceFormatOption = {
    /** 保留几位小数 默认为:2 */
    decimals?: number;
    /** 小数点符号 默认为: '.' */
    decimalPoint?: string;
    /** 千分位符号，默认为: ',' */
    thousandsSeparator?: string;
  };
  const sys = mxpGetSysInfoStore().getSysInfo();
  /** 屏幕宽度 */
  const windowWidth = computed<$SizeUnitStr>(() => (sys.value.windowWidth > 200 ? `${sys.value.windowWidth}px` : '750rpx'));
  /** 顶部安全区高度 */
  const safeTopHeight = computed(() => (props.safeAreaInsetTop ? sys.value.statusBarHeight || 0 : 0));

  const menuInfo = ref(uni.getMenuButtonBoundingClientRect?.() || {});

  onMounted(() => {
    menuInfo.value = uni.getMenuButtonBoundingClientRect?.() || {};
  });

  /** 胶囊按钮占位宽度 (胶囊的宽度 + 胶囊按钮距离右边的距离) */
  const menuButtonWidth = computed(() => {
    let width = 0;
    // #ifdef MP
    if (props.safeAreaInsetRight) {
      const left = menuInfo.value.left;
      width = sys.value.windowWidth - left;
      // #ifdef MP-TOUTIAO
      width += Math.fround(menuInfo.value.width / 2 + 10);
      // #endif
    }
    // #endif

    return width;
  });

  /** 高度 */
  const navHeight = computed(() => `${getHeaderHeight(sys.value.statusBarHeight)}px`);

  const titleLeft = computed(() => `${(sys.value.windowWidth - menuButtonWidth.value - getXPNumber(props.titleWidth, 180)) / 2}px`);

  const newTitleStyle = computed<CSSProperties>(() => {
    const obj: CSSProperties = { color: props.titleColor || props.leftIconColor || '#303133' };

    // #ifdef H5
    obj.fontSize = props.titleFontSize || '16px';
    obj.fontWeight = props.titleFontWeight || 'bold';
    // #endif

    // #ifndef H5
    obj.fontSize = props.titleFontSize || '15px';
    // #endif
    return obj;
  });

  /** 返回 */
  function onBack() {
    emits('onBack');
    if (props.homePath) {
      const pages = getCurrentPages();
      if (pages.length >= 2) {
        uni.navigateBack();
      } else {
        uni.reLaunch({ url: props.homePath });
      }
    } else {
      uni.navigateBack();
    }
  }
</script>

<style lang="scss" scoped>
  .mxp-navbar {
    top: 0;
    left: 0;
    z-index: 9999999;
    display: flex;
    flex-direction: column;
    width: 750rpx;

    .navbar-vessel {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;

      .navbar-view {
        position: relative;
        box-sizing: border-box;
        display: flex;
        flex: 1;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;

        .left-view {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
        }

        .title-view {
          position: absolute;
          top: 0;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
        }

        .right-view {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
